import type { Router } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'
import { permissionApi } from '@/api/permissions'

export function setupRouterGuards(router: Router) {
  router.beforeEach(async (to, from, next) => {
    const authStore = useAuthStore()
    
    // 公开路由直接放行
    const publicRoutes = ['/login', '/register', '/404']
    if (publicRoutes.includes(to.path)) {
      next()
      return
    }

    // 检查登录状态
    const token = localStorage.getItem('token')
    const userData = localStorage.getItem('user')
    
    if (!token || !userData) {
      ElMessage.error('请先登录')
      next('/login')
      return
    }

    try {
      // 恢复用户状态
      if (!authStore.user) {
        const user = JSON.parse(userData)
        authStore.setUser(user)
        authStore.setToken(token)
      }
      
      // 检查是否已有动态路由
      const routes = router.getRoutes()
      const hasUserRoutes = routes.some(route => route.meta?.isDynamic)
      
      if (!hasUserRoutes) {        
        try {
          let menuData = []
          
          // 优先从store缓存获取
          if (authStore.userMenus.length > 0) {
            menuData = authStore.userMenus
          } else {
            // 从API获取
            const response = await permissionApi.getMenuTree()
            if (response.data && Array.isArray(response.data)) {
              menuData = response.data
              authStore.setMenus(menuData)
            }
          }
          
          // 添加动态路由
          if (menuData.length > 0) {
            await addRoutesFromMenus(router, menuData)
            
            // 重新检查目标路由是否存在
            const resolvedRoute = router.resolve(to.path)
            
            if (resolvedRoute.name !== 'NotFound') {
              next()
            } else {
              next('/404')
            }
          } else {
            next('/404')
          }
        } catch (error) {
          console.error('[Router Guard] 加载动态路由失败:', error)
          next('/404')
        }
        return
      }
      
      // 动态路由已存在，直接检查路由
      const resolvedRoute = router.resolve(to.path)
      
      if (resolvedRoute.name === 'NotFound' && to.path !== '/404') {
        next('/404')
      } else {
        next()
      }
      
    } catch (error) {
      console.error('[Router Guard] 路由守卫错误:', error)
      localStorage.clear()
      authStore.logout()
      ElMessage.error('登录状态异常，请重新登录')
      next('/login')
    }
  })
}

// 从菜单数据添加路由的辅助函数
const addRoutesFromMenus = async (router: Router, menus: any[]) => {
  const processMenu = (menu: any, parentMenus: any[] = []) => {
    if (menu.children && menu.children.length > 0) {
      menu.children.forEach((child: any) => processMenu(child, [...parentMenus, menu]))
    }
    
    if (menu.path && menu.component && menu.type === 'MENU') {
      let routePath = menu.path
      if (routePath.startsWith('/')) {
        routePath = routePath.substring(1)
      }
      
      // 生成完整面包屑
      const breadcrumb = ['首页']
      parentMenus.forEach(parent => breadcrumb.push(parent.name))
      breadcrumb.push(menu.name)
      
      const route = {
        path: routePath,
        name: menu.name.replace(/\s+/g, ''),
        component: () => import(/* @vite-ignore */ `../views/${menu.component}`).catch((error) => {
          // 如果有额外的错误信息，也一并打印
          if (error.cause) console.error('错误原因:', error.cause);
          // 如果组件加载失败，跳转到错误页面并传递组件路径信息
          return import('../views/common/ComponentNotFoundView.vue')
        }),
        meta: {
          title: menu.name,
          icon: menu.icon,
          breadcrumb: breadcrumb,
          isDynamic: true,
          componentPath: menu.component // 保存组件路径用于错误显示
        }
      }
      router.addRoute('MainLayout', route)
    }
  }
  
  menus.forEach(menu => processMenu(menu))
}